import axios from "axios";
import {ElMessage, ElMessageBox, ElNotification} from "element-plus";
import errorCode from "./enums/errorCode.js"
import {HttpStatus} from './enums/RespEnum.ts'
import JSONBIG from 'json-bigint'
import router from "../router";

const service = axios.create({
    baseURL: '/api',
    timeout: 50000
});
//处理long类型精度损失的问题
service.defaults.transformResponse = [
    function (data) {
        try {
            // 检查是否是二进制数据
            if (typeof data !== 'string') {
                console.log(data)
                return data;
            }
            // 使用 JSONBIG 解析 JSON 数据
            const json = JSONBIG({
                storeAsString: true
            });
            return json.parse(data);
        } catch (e) {
            // 如果解析失败，直接返回原始数据
            return data;
        }
    }
];
export const isReLogin = {show: false};
//请求拦截器
service.interceptors.request.use((config) => {
    return config
});

//响应拦截器，对结果进行预处理
service.interceptors.response.use((res) => {
        // 二进制数据则直接返回
        if (res.request.responseType === 'blob' || res.request.responseType === 'arraybuffer') {
            return res.data;
        }
        //预设错误信息
        const msg = errorCode[res.data.code] || res.data.msg || errorCode['default'];
        //预处理响应结果，无需再做状态码校验
        if (res.data.code === 401 && router.path !== '/login') {
            if (!isReLogin.show) {
                isReLogin.show = true;
                ElMessageBox.confirm('登录状态已过期，您可以继续留在该页面，或者重新登录', '系统提示', {
                    confirmButtonText: '重新登录',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    isReLogin.show = false;
                    router.push('/login');

                }).catch(() => {
                    isReLogin.show = false;
                });
            }
            return Promise.reject('无效的会话，或者会话已过期，请重新登录。');
        } else if (res.data.code === HttpStatus.SERVER_ERROR) {
            ElMessage({message: msg, type: 'error'});
            return Promise.reject(new Error(msg));
        } else if (res.data.code === HttpStatus.WARN) {
            ElMessage({message: msg, type: 'warning'});
            return Promise.reject(new Error(msg));
        } else if (res.data.code !== HttpStatus.SUCCESS) {
            ElNotification.error({title: msg});
            return Promise.reject('error');
        } else {
            return Promise.resolve(res.data);
        }
    },
    (error) => {
        let {message} = error;
        if (message === 'Network Error') {
            message = '后端接口连接异常';
        } else if (message.includes('timeout')) {
            message = '系统接口请求超时';
        } else if (message.includes('Request failed with status code')) {
            message = '系统接口' + message.substr(message.length - 3) + '异常';
        }
        ElMessage({message: message, type: 'error', duration: 5 * 1000});
        return Promise.reject(error);
    }
);

export default service;